package com.polaris.live.ui.main.live

import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.polaris.live.adapter.live.HomeFollowAdapter
import com.polaris.live.common.cacha.CacheUtil
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.base2.BaseVbFragment
import com.polaris.live.common.network.AppException
import com.polaris.live.common.network.parseState
import com.polaris.live.common.util.DebounceHelper
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.databinding.FragmentLiveFollowRoomBinding
import com.polaris.live.popup.GlobalPopupManager
import com.polaris.live.resp.back_resp.DisplayUserBean
import com.polaris.live.utils.LiveUtils
import com.polaris.live.utils.StartLiveProxy
import com.polaris.live.utils.interfaces.OnAutoRefreshListener
import com.polaris.live.utils.route.RoutePath
import com.polaris.live.utils.route.Router
import com.polaris.live.viewmodel.LiveFollowRoomViewModel
import com.polaris.live.widget.refresh.ErrorView

/**
 * LiveFollowRoomFragment 直播关注界面
 *
 * @author Created by 天晴 on 2024/12/26/020 14:15
 */
class LiveFollowRoomFragment : BaseVbFragment<LiveFollowRoomViewModel, FragmentLiveFollowRoomBinding>(),
    OnAutoRefreshListener {

    private val mAdapter by lazy { HomeFollowAdapter() }
    private val mRecommendAdapter by lazy { HomeFollowAdapter() }

    private var lastRefreshTime: Long? = null
    private var refreshTime = 1000
    override fun initView(savedInstanceState: Bundle?) {
        mBinding.recycler.apply {
            layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
            adapter = mAdapter
            itemAnimator = null
        }
        mBinding.recycler2.apply {
            layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
            adapter = mRecommendAdapter
            itemAnimator = null
        }
        initObserve()
        initListener()
        onRefresh()
    }

    private fun onRefresh() {
        mBinding.refresh.setOnRefreshListener {
            mViewModel.pageNumber = 0
            mViewModel.getLiveData()
        }

        mBinding.refresh.setOnLoadMoreListener {
            mViewModel.pageNumber += 1
            mViewModel.getLiveData()
        }
    }

    override fun initData() {
        super.initData()
        mViewModel.getLiveData()
    }

    private fun initObserve() {
        mViewModel.livesLiveData.observe(this) { resultState ->
            mBinding.widgetLoading.visibility = View.GONE
            parseState(resultState, {
                lastRefreshTime = CacheUtil.getServerTime()
                //如果number = 0 就可以理解为刷新了
                if (mViewModel.pageNumber == 0) {
                    mAdapter.setList(it.list)
                    if (it.list.isNotEmpty()) {
                        mBinding.widgetEmpty.visibility = View.GONE
                    }
                } else {
                    mAdapter.addData(it.list)
                }
            }, {
                showError(it)
            })
            mBinding.refresh.finishRefresh()
            mBinding.refresh.finishLoadMore()
        }
        mViewModel.recommendData.observe(this) { resultState ->
            mBinding.widgetLoading.visibility = View.GONE
            parseState(resultState, {
                if (it.isEmpty()) {
                    mBinding.recommendedTv.visibility = View.GONE
                } else {
                    mBinding.recommendedTv.visibility = View.VISIBLE
                    mBinding.widgetEmpty.visibility = View.GONE
                }
                mRecommendAdapter.setList(it)
            })
        }
        mViewModel.notHaveData.observe(this) {
            mBinding.widgetLoading.visibility = View.GONE
            mBinding.widgetEmpty.visibility = View.VISIBLE
        }
        mViewModel.mPartyRoomLiveData.observe(this) { resultState ->
            parseState(resultState, {
                if (it.roomId?.isNotEmpty() == true) {
                    val liveType = UserManager.getUser().live?.liveType
                    StartLiveProxy.builder(this)
                        .recoverLive(mViewModel, liveType, it.roomId)
                } else {
                    //开启派对
                    Router.builder(RoutePath.SET_PARTY_COVER_ACTIVITY)
                        .navigation(requireActivity())
                }
            })
        }
    }

    fun initListener() {
        mAdapter.setOnItemClickListener { _, _, position ->
            DebounceHelper.singleClick {
                val item = mAdapter.getItemOrNull(position) ?: return@singleClick
                if (item is DisplayUserBean) {
                    if (item.base.userId == UserManager.getUserId()) {
                        mViewModel.getPartyRoom()
                    } else {
                        GlobalPopupManager.showCompletePopup(requireContext(), isOk = {
                            LiveUtils.invokeSpectator(requireContext(), item)
                        })
                    }
                }
            }
        }
        mRecommendAdapter.setOnItemClickListener { _, _, position ->
            DebounceHelper.singleClick {
                val item = mRecommendAdapter.getItemOrNull(position) ?: return@singleClick
                if (item is DisplayUserBean) {
                    if (item.base.userId == UserManager.getUserId()) {
                        mViewModel.getPartyRoom()
                    } else {
                        GlobalPopupManager.showCompletePopup(requireContext(), isOk = {
                            LiveUtils.invokeSpectator(requireContext(), item)
                        })
                    }
                }
            }
        }
        mBinding.ivStartParty.setOnSingleClickListener {
            LiveUtils.openPartyChecking(requireContext(), mViewModel)
        }
    }

    private fun showError(appException: AppException) {
        if (mAdapter.data.isNotEmpty()) {
            ToastGravity.showGravity(appException.errorMsg)
        }
        //当number是0  并且没有关注和推荐的时候  展示空布局
        if (mViewModel.pageNumber == 0 && mAdapter.data.isEmpty() && mRecommendAdapter.data.isEmpty()) {
            mBinding.widgetEmpty.visibility = View.VISIBLE
        }
    }

    override fun onResume() {
        toRefresh()

        super.onResume()
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)

        if (!hidden) {
            toRefresh()
        }
    }

    private fun toRefresh() {
        if (isLoadData()) {
            val lastRefreshTime = lastRefreshTime
            if (lastRefreshTime == null || CacheUtil.getServerTime() - lastRefreshTime > 5 * 60 * refreshTime) {
                onAutoRefresh()
            }
        }
    }

    override fun onAutoRefresh() {
        if (!isCreated() || !isLoadData()) {
            return
        }

        mBinding.recycler.scrollToPosition(0)
        mBinding.refresh.autoRefresh()
    }

}